// pages/volunteer/product-detail.js

Page({
  data: {
    // 商品信息
    product: {
      id: 1,
      name: '精美陶瓷马克杯',
      brief: '采用优质陶瓷材质，手感细腻，保温效果好，适合日常使用和礼品赠送。',
      description: '这是一款精心设计的陶瓷马克杯，采用优质高岭土制作，经过1300度高温烧制，具有优异的保温性能和耐用性。杯身采用人体工学设计，握感舒适，容量适中，适合各种饮品使用。\n\n产品特点：\n• 优质陶瓷材质，安全无毒\n• 1300度高温烧制，耐用性强\n• 人体工学设计，握感舒适\n• 保温效果好，适合各种饮品\n• 精美包装，适合送礼',
      images: ['/images/杯子.png', '/images/1.jpg', '/images/杯子.png'],
      points: 50,
      stock: 100,
      redeemed: 25,
      sales: 150,
      categoryName: '日用品',
      brand: '爱道公益',
      weight: '280g',
      size: '12cm × 8cm',
      material: '优质陶瓷',
      warranty: '1年质保',
      specifications: [
        { name: '材质', value: '优质陶瓷' },
        { name: '容量', value: '350ml' },
        { name: '尺寸', value: '高12cm × 直径8cm' },
        { name: '重量', value: '280g' },
        { name: '颜色', value: '白色' },
        { name: '包装', value: '精美礼盒' },
        { name: '品牌', value: '爱道公益' },
        { name: '质保', value: '1年质保' }
      ],
      // 新增：商品标签
      tags: ['热销', '新品', '包邮'],
      // 新增：商品服务
      services: ['7天无理由退换', '正品保证', '快速发货'],
      // 新增：商品推荐
      recommendations: [
        { id: 2, name: '青色马克杯', image: '/images/1.jpg', points: 60 },
        { id: 3, name: '金色手柄杯', image: '/images/杯子.png', points: 80 },
        { id: 4, name: '棕色陶瓷杯', image: '/images/杯子.png', points: 70 }
      ]
    },
    
    // 页面状态
    currentImageIndex: 0,
    quantity: 1,
    maxQuantity: 10,
    totalPoints: 0,
    remainingPoints: 0,
    canRedeem: false,
    showRedeemModal: false,
    showShareModal: false,
    showSpecsModal: false,
    
    // 用户信息
    userInfo: {},
    
    // 页面滚动状态
    scrollTop: 0,
    
    // 加载状态
    loading: false,
    
    // 收货地址
    selectedAddress: null,
    addressList: []
  },

  onLoad(options) {
    // 获取商品ID
    if (options.id) {
      this.setData({
        productId: options.id
      });
      this.loadProductDetail(options.id);
    }
    
    this.loadUserData();
    this.loadAddressList();
  },

  onShow() {
    this.refreshUserData();
    this.loadAddressList();
  },

  // 加载商品详情
  loadProductDetail(productId) {
    this.setData({ loading: true });
    
    // 这里应该调用API获取商品详情
    // 暂时使用模拟数据
    console.log('加载商品详情:', productId);
    
    setTimeout(() => {
      this.setData({ loading: false });
    }, 500);
  },

  // 加载用户数据
  loadUserData() {
    const userData = wx.getStorageSync('volunteerUserData') || {};
    this.setData({
      userInfo: userData
    });
  },

  // 刷新用户数据
  refreshUserData() {
    this.loadUserData();
    this.calculatePoints();
  },

  // 加载地址列表
  loadAddressList() {
    const addressList = wx.getStorageSync('volunteerAddresses') || [];
    const selectedAddress = addressList.find(addr => addr.isDefault) || addressList[0];
    
    this.setData({
      addressList,
      selectedAddress
    });
  },

  // 计算积分
  calculatePoints() {
    const totalPoints = this.data.quantity * this.data.product.points;
    const remainingPoints = (this.data.userInfo.currentPoints || 0) - totalPoints;
    const canRedeem = remainingPoints >= 0 && this.data.product.stock > 0;
    
    this.setData({
      totalPoints,
      remainingPoints,
      canRedeem
    });
  },

  // 图片轮播切换
  onSwiperChange(e) {
    this.setData({
      currentImageIndex: e.detail.current
    });
  },

  // 预览图片
  previewImage(e) {
    const current = e.currentTarget.dataset.src;
    wx.previewImage({
      current,
      urls: this.data.product.images
    });
  },

  // 减少数量
  decreaseQuantity() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      });
      this.calculatePoints();
    }
  },

  // 增加数量
  increaseQuantity() {
    if (this.data.quantity < this.data.maxQuantity && this.data.quantity < this.data.product.stock) {
      this.setData({
        quantity: this.data.quantity + 1
      });
      this.calculatePoints();
    }
  },

  // 兑换商品
  redeemProduct() {
    // 检查用户信息是否完整
    const userData = wx.getStorageSync('volunteerUserData') || {};
    if (!userData.name || !userData.volunteerId) {
      wx.showModal({
        title: '提示',
        content: '请先完善个人信息后再进行兑换',
        confirmText: '去完善',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/volunteer/profile'
            });
          }
        }
      });
      return;
    }

    // 检查是否有收货地址
    if (!this.data.selectedAddress) {
      wx.showModal({
        title: '提示',
        content: '请先添加收货地址后再进行兑换',
        confirmText: '去添加',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/volunteer/address'
            });
          }
        }
      });
      return;
    }

    // 重置数量为1
    this.setData({
      quantity: 1
    });
    this.calculatePoints();

    this.setData({
      showRedeemModal: true
    });
  },

  // 关闭兑换弹窗
  closeRedeemModal() {
    this.setData({
      showRedeemModal: false
    });
  },

  // 选择地址
  selectAddress() {
    wx.navigateTo({
      url: '/pages/volunteer/address?select=true',
      events: {
        // 监听地址选择结果
        addressSelected: (address) => {
          this.setData({
            selectedAddress: address
          });
        }
      }
    });
  },

  // 确认兑换
  confirmRedeem() {
    if (!this.data.canRedeem) {
      if (this.data.remainingPoints < 0) {
        wx.showModal({
          title: '积分不足',
          content: `需要${this.data.totalPoints}积分，当前${this.data.userInfo.currentPoints}积分。快去完成签到和任务获取更多积分吧！`,
          confirmText: '去赚积分',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              // 跳转到志愿者详情页面
              wx.navigateTo({
                url: '/pages/volunteer/volunteer-detail'
              });
            }
          }
        });
        return;
      } else if (this.data.product.stock <= 0) {
        wx.showToast({
          title: '商品库存不足',
          icon: 'none'
        });
        return;
      }
    }

    wx.showLoading({
      title: '兑换中...'
    });

    // 模拟兑换过程
    setTimeout(() => {
      wx.hideLoading();

      // 扣除积分
      const userData = wx.getStorageSync('volunteerUserData') || {};
      userData.currentPoints -= this.data.totalPoints;
      wx.setStorageSync('volunteerUserData', userData);

      // 创建订单
      const order = {
        id: Date.now(),
        productId: this.data.product.id,
        productName: this.data.product.name,
        productImage: this.data.product.images[0],
        quantity: this.data.quantity,
        points: this.data.totalPoints,
        status: 'pending',
        createTime: new Date().toISOString(),
        estimatedDelivery: this.getEstimatedDelivery(),
        address: this.data.selectedAddress
      };

      // 保存订单
      const orders = wx.getStorageSync('volunteerOrders') || [];
      orders.unshift(order);
      wx.setStorageSync('volunteerOrders', orders);

      // 更新商品库存
      this.setData({
        'product.stock': this.data.product.stock - this.data.quantity,
        'product.redeemed': this.data.product.redeemed + this.data.quantity,
        showRedeemModal: false
      });

      // 刷新用户数据
      this.refreshUserData();

      wx.showModal({
        title: '兑换成功',
        content: '您的订单已提交，我们会尽快为您发货',
        confirmText: '查看订单',
        cancelText: '继续兑换',
        success: (res) => {
          if (res.confirm) {
            // 跳转到我的订单页面
            wx.navigateTo({
              url: '/pages/volunteer/orders'
            });
          } else {
            // 继续兑换，刷新页面数据
            this.refreshUserData();
          }
        }
      });
    }, 1500);
  },

  // 获取预计送达时间
  getEstimatedDelivery() {
    const now = new Date();
    const deliveryDate = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000); // 7天后
    return deliveryDate.toLocaleDateString('zh-CN');
  },

  // 跳转到商品评价页面
  goToReviews() {
    wx.navigateTo({
      url: `/pages/volunteer/product-reviews?id=${this.data.product.id}`
    });
  },

  // 显示规格详情
  showSpecsDetail() {
    this.setData({
      showSpecsModal: true
    });
  },

  // 关闭规格弹窗
  closeSpecsModal() {
    this.setData({
      showSpecsModal: false
    });
  },

  // 显示分享弹窗
  showShare() {
    this.setData({
      showShareModal: true
    });
  },

  // 关闭分享弹窗
  closeShareModal() {
    this.setData({
      showShareModal: false
    });
  },

  // 跳转到推荐商品
  goToRecommendation(e) {
    const productId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/volunteer/product-detail?id=${productId}`
    });
  },

  // 跳转到志愿者详情页面
  goToVolunteerDetail() {
    wx.navigateTo({
      url: '/pages/volunteer/volunteer-detail'
    });
  },

  // 页面滚动事件
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },

  // 分享
  onShareAppMessage() {
    return {
      title: `${this.data.product.name} - 积分商城`,
      path: `/pages/volunteer/product-detail?id=${this.data.product.id}`,
      imageUrl: this.data.product.images[0]
    };
  },

  onShareTimeline() {
    return {
      title: `${this.data.product.name} - 积分商城`,
      imageUrl: this.data.product.images[0]
    };
  }
});

